<?php
require_once 'phpQuery/phpQuery.php';


class YahooTwBidException extends Exception {}

class YahooTwBid
{
  private $_obj_list_view_pattern = 'http://tw.rd.yahoo.com/referurl/bid//list/cat/[0-9]*/[0-9]*//aidtitle/\*http://tw.page.bid.yahoo.com/tw/auction/([a-z0-9]*)';
  private $_list_uri              = 'http://tw.bid.yahoo.com/tw/%s-category-leaf.html?n=50&display=imagetext&b=%d';
  private $_current_price_pattern = '目前出價：([0-9,]*元)';
  private $_direct_price_pattern  = '直購價：([0-9,]*元)?';
  private $_ship_fee              = '運費：(([0-9]*元)|(免運費))?';
  private $_location_pattern      = '商品所在地：([^\<\>]*)';
  private $_lists_array           = array();
  private $_proxies_array         = array();

  public function __construct ($use_pyproxy = false) {
    $this->_use_proxy = (bool)$use_pyproxy;
    
    if ($this->_use_proxy === true) {
      require_once dirname(__FILE__).'/config.php';
      $this->_proxies_array = $config['proxies'];
    }


  }

  public function get_list ($catid, $bind_func) {
    $i  = 0;
    $output = array();
    
    while (true) {
      try {
        $uri            = sprintf($this->_list_uri, $catid, ($i * 50) + 1);
        $html           = $this->get_html($uri);
        $parse_results  = $this->_parse_object($html);
        
        if (empty($parse_results)) {
          break;
        }
        $output = array_merge($output, $parse_results);
        
      } catch (YahooTwBidException $e) {
        $code = (int)$e->getCode();
        switch ($code) {
          case 500: // 無法擷取到html
            echo '['.date('Y-m-d H:i:s').'] '.$e->getMessage()."\n";
            continue;
          case 501: // 不是底層分類，所以無法擷取到物件資料
            echo '['.date('Y-m-d H:i:s').'] '.$e->getMessage()."\n";
            return false;
        }
      }
    }
    return call_user_func_array($bind_func, array('data'=>$output));
  }

  protected function get_html ($uri) {
    $url  = $this->_generate_request_uri($uri);
    $ch   = curl_init($uri);
    curl_setopt_array($ch, array(
      CURLOPT_RETURNTRANSFER  =>  1,
      CURLOPT_TIMEOUT         =>  5,
      CURLOPT_FOLLOWCATION    =>  false,
    ));
    $result = curl_exec($ch);
    $info   = curl_getinfo($ch);
    curl_close($ch);
    if ($info['http_code'] < 200 || $info['http_code'] > 299) {
      throw new YahooTwBidException("Cannot fetch html", 500);
    }
    return $html;
  }
  
  private function _parse_object ($html) {
    $dataset  = array();
    preg_match_all($this->_obj_list_view_pattern, $html, $match_items_id);
    if (!empty($match_items_id)) {
    }
  }
  
  // 
  private function _generate_request_uri ($uri) {
    if ($this->_use_proxy === false) {
      return $uri;
    }
    if (empty($this->_proxies_array)) {
      return $uri;
    }
    $proxy_id   = array_rand($this->_proxies_array, 1);
    $proxy      = (substr($this->_proxies_array[$proxy_id], -1, 1) !== '/') ? ($this->_proxies_array[$proxy_id].'/') : $this->_proxies_array[$proxy_id];
    return $proxy.'u?purl='.rawurlencode(base64_encode(strrev($uri)));
  }
  
}

class YahooTwBidObject extends YahooTwBid
{
  public function __construct () {
    parent::__construct();
  }
  
  static public function get_object ($obj_id) {
  }
  
}

?>
